<template>
  <el-result v-if="!contestId" icon="info" title="没有进行中的考试">
    <template #extra>
      <br />
      <br />
      <el-button @click="goBack()" type="primary">查看我的考试</el-button>
    </template>
  </el-result>
  <el-result
    v-else-if="contestId && !compairTime()"
    icon="primary"
    title="考试尚未开始"
  >
    <template #extra>
      <text> 距离考试开始还有</text>
      <el-countdown format="HH:mm:ss" :value="timeToStart"> </el-countdown>
      <br />
      <el-button @click="goBack()" type="primary">查看我的考试</el-button>
    </template>
  </el-result>
    <el-result v-else-if="isEnd()" icon="info" title="考试已结束">
    <template #extra>
      <p>请点击查看积分排名</p>
      <br />
      <el-button @click="router.push('/contest/end')" type="primary">前往积分榜</el-button>
    </template>
  </el-result>
  <el-result v-else icon="success" title="考试已开始">
    <template #extra>
      <p>请点击按钮进入考试</p>
      <br />
      <el-button @click="startContest()" type="success">开始考试</el-button>
    </template>
  </el-result>
  <contestId />
</template>
<script setup lang="ts">
import contestQuery from "@/api/modules/contestQuery";
import router from "@/router";
import { userInfo } from "@/stores/userinfo";
const userStore = userInfo();
const timeToStart = ref();
const timeToEnd = ref();
const contestId = ref(null);
onMounted(() => {
  contestId.value = userStore.onGoingContest;
  if (contestId.value) {
    resetTime();
    setEndTime();
  }
});
//时间到跳转到考试页面
const startContest = () => {
  router.push("/contest/start");
};
//查询考试开始时间
const resetTime = () => {
  contestQuery.queryStartTime({ contestId: contestId.value }).then((res) => {
    timeToStart.value = new Date(res.data as string);
  });
};
const setEndTime = () => { 
  contestQuery.queryEndTime({ contestId: contestId.value }).then((res) => {
    timeToEnd.value = new Date(res.data as string);
  });
};
//返回我的考试列表
const goBack = () => {
  router.replace("/contest/list");
};
//判断考试是否开始，开始返回false
const compairTime = () => {
  if (Date.now() > timeToStart.value.getTime()) {
    return true;
  }
};
//判断考试是否结束
const isEnd = () => {
    if (Date.now() > timeToEnd.value.getTime()) {
      return true;
    }
};
</script>
